<?php

// Copyright © 2017 Jorge Maldonado Ventura
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

/**
 * Return first results page from DuckDuckGo.
 *
 * Gets the firsts result page from the URL obtained suplying the search string
 * and the language for which the results are searched. It returns a string
 * cointaining its HTML code.
 *
 * @see https://duckduckgo.com/params Syntax of DuckDuckGo results settings.
 *
 * @param  string $searchStr
 * @param  string $lang
 */
function getSearchResultsPage($searchStr, $lang='es-es')
{
    $url = sprintf('https://duckduckgo.com/html/?q=%s&kl=%s', urlencode($searchStr), urlencode($lang));
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
    curl_setopt($ch, CURLOPT_TIMEOUT, 40);
    curl_setopt($ch, CURLOPT_COOKIEFILE, "cookie.txt");
    curl_setopt($ch, CURLOPT_URL, $url);
    $output = curl_exec ($ch);
    ob_start();
    return $output;
    //clean buffer
    ob_end_clean();
    curl_close ($ch);
}

/**
 * Return the matches against given sentence or sentences.
 *
 * If there is not any result, it returns 0; if there is an error, it returns
 * false; else it returns a list that contains an associative array for every
 * result that contanis:
 *   ['matches']   number of matches
 *   ['abstract']  the abstract of the result
 *   ['url']       the URL of the result
 */
function checkPlagiarism($sentence)
{
    $html = getSearchResultsPage($sentence);
    $resultsFound = preg_match_all('/<a class="result__snippet" href="(.*)">(.*)<\/a>/U', $html, $matches, PREG_SET_ORDER);
    if ($resultsFound == false) {
        return false;
    } else if($resultsFound == 0) {
        return 0;
    } else {
        $plagiarismResults = [];
        foreach ($matches as $val) {
            $plagiarismResults[] = array('matches' => countB($val[2]), 'abstract' => $val[2], 'url' => $val[1]);
        }
        return $plagiarismResults;
    }
}

/**
 * Return the number of <b> occurrences found in a string.
 */
function countB($string)
{
    $words = explode(' ', $string);
    $matches = 0;
    foreach ($words as $word) {
        if (strstr($word, '<b>')){
            $matches += 1;
        }
    }
    return $matches;
}
